package com.aida.evil.eda.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Adapter.CommonAdapter;
import com.aida.evil.eda.Adapter.ViewHolder;
import com.aida.evil.eda.Answer.AnswerActivity;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.SQL.Eda_SQL.Eda_Sql;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.yalantis.phoenix.PullToRefreshView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/****************************************************
 * com.aida.evil.eda.fragment.Eda
 * 作者：白雨濃  evil
 * 时间：16-2-11 21:42
 * 邮箱：evilbai@foxmail.com
 * 页面用途：主界面 首页 界面fragment
 * 包含 首页ListView的Adapter和ItemBean
 * 继承于Eda_item_network，进行网络框架加载，Eda_item_network继承了Fragment
 ****************************************************/

/**
 * 2016年03月20日20:20:34 重写
 */
public class Eda extends Fragment
{
    /*加载item文字内容*/
    private static final String URL =
            "http://" + NetworkData.ServiceIP + "/EdaItem?"
                    + "userPhoneNum=" + UserData.DATA_PHONENUM + "&LastItem=";
    /*加载item图片内容*/
    private static final String IMGURL =
            "http://" + NetworkData.ServiceIP + "/ItemImg?ItemImg=";
    /*结束加载，上传最后一个ItemID*/
    private static String FINISHURL = "http://" + NetworkData.ServiceIP + "/UserData?";
    /*广播用的ACTION标志位*/
    public static String EDA_ACTION = "EDAREMOVE";


    /*列表最大长度*/
    private static final int MAXLISTSIZE = 20;

    private static int lastItemID = 0;/*最后一个Item的ID*/

    private PullToRefreshView pullToRefreshView;
    //private FunGameRefreshView refreshView;

    private View view;/*fragment的view*/
    private ListView listView;/*主界面的列表ListView 显示答题列表*/
    private Eda_Adapter adapter;/*ListView的Adapter*/


    private ArrayList<Eda_ItemBeans> eda_itemlist = new ArrayList<>();/*保存Item项目的数组*/

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        firstload();/*首次加载*/
    }

    /**
     * fragment的view初始化
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return view
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.mainactivity_fragment_eda, container, false);
        initView();/*查找控件*/

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            adapter = new Eda_Adapter(getContext(), eda_itemlist, R.layout.mainactivity_fragment_eda_listview_item);
        else
            adapter = new Eda_Adapter(getContext(), eda_itemlist, R.layout.mainactivity_fragment_eda_listview_item_4_4);

        listView.setAdapter(adapter);

        refreshView();/*刷新监听*/
        itemIntent();/*item跳转*/

        return view;
    }


    /**
     * item点击跳转到答题界面
     */
    private void itemIntent()
    {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id)
            {
                Eda_ItemBeans eda_itemBeans = eda_itemlist.get(position);
                /*eda_itemlist.remove(position);
                handler.sendEmptyMessage(0);*//*调用刷新线程*//*
                *//*如果eda_itemlist为0，强制刷新*//*
                if (eda_itemlist.size() == 0)
                {
                    toNetWork(lastItemID);
                }*/

                //跳转
                Intent intent = new Intent(getActivity(), AnswerActivity.class);
                intent.putExtra("itemTitle", eda_itemBeans.itemTitle);
                intent.putExtra("itemID", eda_itemBeans.itemID);
                intent.putExtra("position", position);
                startActivity(intent);
                getActivity().overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);
            }
        });
    }

    /**
     * 根据Id查找控件
     */
    private void initView()
    {
        listView = (ListView) view.findViewById(R.id.mainactivity_fragment_eda_listview);
        //refreshView = (FunGameRefreshView) view.findViewById(R.id.mainactivity_fragment_eda_funGameRefreshView);
        pullToRefreshView = (PullToRefreshView) view.findViewById(R.id.mainactivity_fragment_eda_pullToRefreshView);
    }


    /**
     * 首次加载
     * 如果数据库里有值，读取数据库中的值
     * 如果数据库中无值，获取网络中的值
     */
    private void firstload()
    {
        Eda_Sql eda_sql = new Eda_Sql(getContext());
        List<com.aida.evil.eda.SQL.Eda_SQL.Item> items = eda_sql.queryAll();
        if (items.size() == 0)
        {
            Log.i("网络加载", "网络加载");
            toNetWork(0);//数据库中无值，获取网络
        }
        else
        {
            Log.i("本地加载", "本地加载");
            com.aida.evil.eda.SQL.Eda_SQL.Item item = null;
            for (int i = 0; i < items.size(); i++)
            {
                item = items.get(i);
                eda_itemlist.add(
                        new Eda_ItemBeans(
                                item.getItemID(),
                                item.getItemImg(),
                                item.getItemTitle(),
                                item.getItemContext()));
            }
            lastItemID = item.getItemID();
        }
    }

    /**
     * 刷新监听
     */
    private void refreshView()
    {
       /* refreshView.setOnRefreshListener(new FunGameRefreshView.FunGameRefreshListener()
        {
            @Override
            public void onRefreshing()
            {
                toNetWork(lastItemID);
            }
        });*/
        pullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                pullToRefreshView.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        pullToRefreshView.setRefreshing(true);
                        toNetWork(lastItemID);
                    }
                }, 1000);
            }
        });
    }

    /**
     * 刷新listview
     */
    Handler refreshHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            adapter.notifyDataSetChanged();
            //refreshView.finishRefreshing();
            pullToRefreshView.setRefreshing(false);
        }
    };

    /**
     * 网络请求
     */
    private void toNetWork(int lastItemID)
    {
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            ItemList itemList;

            /**
             * 请求成功
             * @param response 返回String值
             */
            @Override
            public void reqSuccess(String response)
            {
                /*解析JSON*/
                {
                    Type type = new TypeToken<ItemList>()
                    {
                    }.getType();

                    itemList = new Gson().fromJson(response, type);
                }
                /*解析ItemList*/
                {
                    if (itemList != null)
                    {
                        if (itemList.userPhoneNum.equals(UserData.DATA_PHONENUM)
                                && itemList.itemSize != 0)
                        {
                            listSize(itemList.items);/*限制列表最大长度*/
                        }
                        else
                        {
                            CustomSuperActivityToast.makeText(getActivity(), "啊欧，暂时没有东西了，稍后再试试吧！", "好吧……").show();
                        }
                    }
                }
                refreshHandler.sendEmptyMessage(0);
            }

            /**
             * 请求失败
             * @param error
             */
            @Override
            public void reqError(String error)
            {
                CustomSuperActivityToast.makeText(getActivity(), "刷新失败", "刷新").show();
                refreshHandler.sendEmptyMessage(0);
            }
        };

        VolleyHttpRequest.String_request(URL + lastItemID, stringVolleyHandler);
    }


    /**
     * 限制列表最大长度
     * 判断当前页面的item数目是否超过最大限度，超过最大限度的话，移除底下的item
     */
    private void listSize(ArrayList<Item> items)
    {
        if (eda_itemlist.size() > MAXLISTSIZE)
        {
            //移除item，移除最下面的item，指针值为eda_items的大小减去1，新添加了多少个，移除多少个
            for (int i = 0; i < items.size(); i++)
            {
                eda_itemlist.remove(eda_itemlist.size() - 1);
            }
            Item item = null;
            for (int i = 0; i < items.size(); i++)
            {
                item = items.get(i);
                eda_itemlist.add(0, new Eda_ItemBeans
                        (item.itemID, item.itemImg, item.itemTitle, item.itemContext));
            }
            lastItemID = item.itemID;//得到最后一个Item的ID，传递给服务器，服务器根据此Id向下给用户传递
        }
        else
        {
            Item item = null;
            for (int i = 0; i < items.size(); i++)
            {
                item = items.get(i);
                eda_itemlist.add(0, new Eda_ItemBeans
                        (item.itemID, item.itemImg, item.itemTitle, item.itemContext));
            }
            lastItemID = item.itemID;//得到最后一个Item的ID，传递给服务器，服务器根据此Id向下给用户传递
        }
    }

    /**
     * 结束加载
     * 1.上传最后一个item的ID
     * 2.将itemList保存到数据库
     */
    private void finishload()
    {
        /*上传*//*
        {

            VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
            {
                @Override
                public void reqSuccess(String response)
                {

                }

                @Override
                public void reqError(String error)
                {

                }
            };

            Map<String, String> map = new HashMap<>();
            map.put("userIMEI", "" + UserData.DATA_用户IMEI);
            map.put("LastItemID", "" + lastItemID);
            Log.i("最后", "" + lastItemID);
            VolleyHttpRequest.String_request(FINISHURL, map, stringVolleyHandler);
        }*/
        /*保存数据库，属于耗时进程，写入线程中*/
        {
            final Context context = getContext();
            Thread thread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    Eda_Sql eda_sql = new Eda_Sql(context);
                    Eda_ItemBeans eda_itemBeans;

                    eda_sql.deleteAll();//先删除全部，避免残留
                    for (int i = 0; i < eda_itemlist.size(); i++)
                    {
                        eda_itemBeans = eda_itemlist.get(i);
                        eda_sql.update(i, eda_itemBeans.itemID
                                , eda_itemBeans.itemImg
                                , eda_itemBeans.itemTitle
                                , eda_itemBeans.itemContext);
                    }
                    eda_sql = null;
                    eda_itemBeans = null;
                }
            });
            thread.start();
        }
    }


    /***************************************************
     * 广播
     * 作用：答题点击提交时，删除该题目，并且刷新列表
     */

    /**
     * 结束广播，并写入数据库
     */
    @Override
    public void onDestroy()
    {
        super.onDestroy();
        finishload();
        getContext().unregisterReceiver(broadcastReceiver);
    }

    /**
     * 注册广播
     */
    @Override
    public void onResume()
    {
        super.onResume();

        IntentFilter intentFilter = new IntentFilter(EDA_ACTION);
        getContext().registerReceiver(broadcastReceiver, intentFilter);
    }

    /**
     * 广播接收者，接收到广播的item值，删除该值并刷新列表
     */
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            int position = intent.getIntExtra("position", 0);
            eda_itemlist.remove(position);/*删除指定元素，不是下标*/

            handler.sendEmptyMessage(0);/*调用刷新线程*/
            /*如果eda_itemlist为0，强制刷新*/
            if (eda_itemlist.size() == 0)
            {
                toNetWork(lastItemID);
            }
        }
    };

    /**
     * 刷新线程
     */
    private Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            adapter.notifyDataSetChanged();
        }
    };

    /********************************
     * 内部类
     * 应用于ListView的Adapter
     * 继承万能适配器 泛型为ItemBean
     ********************************/
    private class Eda_Adapter extends CommonAdapter<Eda_ItemBeans>
    {


        public Eda_Adapter(Context context, List<Eda_ItemBeans> itemBean_list, int itemLayoutResId)
        {
            super(context, itemBean_list, itemLayoutResId);
        }

        @Override
        public void convert(ViewHolder viewHolder, Eda_ItemBeans item)
        {
            ImageView imageView = viewHolder.getView(R.id.eda_listview_item_imageView);
            TextView title = viewHolder.getView(R.id.eda_listview_item_title);
            TextView context = viewHolder.getView(R.id.eda_listview_item_context);

            Picasso.with(this.context)
                    .load(IMGURL + item.itemImg)
                    .placeholder(R.mipmap.loading)
                    .into(imageView);

            title.setText(item.itemTitle);
            context.setText(item.itemContext);
        }
    }

    /**
     * ItemBeans
     */
    private class Eda_ItemBeans
    {
        protected int itemID;
        protected String itemImg;
        protected String itemTitle;
        protected String itemContext;

        public Eda_ItemBeans(int itemID, String itemImg, String itemTitle, String itemContext)
        {
            this.itemID = itemID;
            this.itemImg = itemImg;
            this.itemTitle = itemTitle;
            this.itemContext = itemContext;
        }
    }

    /**
     * 包含IMEI，item列表数目，item列表
     */
    private class ItemList
    {
        protected String userPhoneNum;/* 发送IMEI，判断JSON准确性 */
        protected int itemSize;/* 该JSON大小，方便使用 */
        protected ArrayList<Item> items = new ArrayList<>();
    }

    /**
     * 包含item列表内的内容（ID，标题，内容）
     */
    protected class Item
    {
        protected int itemID;
        protected String itemImg;
        protected String itemTitle;
        protected String itemContext;
    }

}




















